package com.wlstock.funi.testcase;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.StrictMode;
import android.test.AndroidTestCase;
import android.util.Log;

public class HttpLogTest extends AndroidTestCase {
	public static String TAG = "TESTCASE";
	StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
	
	public void getCookie() {
		try {
			HttpClient client = new DefaultHttpClient();
			HttpGet requestGet = new HttpGet(
					"https://etrade.cs.ecitic.com/ymtrade/login/login.jsp?ssl=false&ftype=pro");

			// Host: etrade.cs.ecitic.com
			// Connection: keep-alive
			// Cache-Control: max-age=0
			// Accept:
			// text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
			// Upgrade-Insecure-Requests: 1
			// User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64)
			// AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86
			// Safari/537.36
			requestGet.addHeader("Connection", "keep-alive");
			requestGet.addHeader("Cache-Control", "max-age=0");
			requestGet
					.addHeader("Accept",
							"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			requestGet.addHeader("Referer",
					"https://etrade.cs.ecitic.com/ymtrade/login/login.jsp");
			requestGet.addHeader("Accept-Encoding", "gzip, deflate, sdch");
			requestGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");

			HttpResponse response = client.execute(requestGet);

			if (response.getStatusLine().getStatusCode() == 200) {
				String cookie = setCookie(response);
				Log.i(TAG, cookie);
				
//				Accept:image/webp,image/*,*/*;q=0.8
//				Accept-Encoding:gzip, deflate, sdch
//				Accept-Language:zh-CN,zh;q=0.8,en;q=0.6
//				Connection:keep-alive
//				Cookie:JSESSIONID=sZBDWcYV6MDW1ZnG5kXDJCHkJ2khZmJSXN1GPyknQdST2fmQvs1T!1036719599!-1780973960; ssl=etrade-ssl-2
//				Host:etrade.cs.ecitic.com
//				Referer:https://etrade.cs.ecitic.com/ymtrade/login/login.jsp?ssl=false&ftype=pro
//				User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36
				double random = Math.random();
				HttpGet erCodeGet = new HttpGet("https://etrade.cs.ecitic.com/ymtrade/pic/Kaptcha.jpg?ran="+random);
				erCodeGet.addHeader("Accept", "image/webp,image/*,*/*;q=0.8");
				erCodeGet.addHeader("Accept-Encoding", "gzip, deflate, sdch");
				erCodeGet.addHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
				erCodeGet.addHeader("Connection", "keep-alive");
				erCodeGet.addHeader("Referer", "https://etrade.cs.ecitic.com/ymtrade/login/login.jsp?ssl=false&ftype=pro");
				erCodeGet.addHeader("Cookie",cookie);
				
				HttpResponse erCodeResponse = client.execute(erCodeGet);
				
				if (erCodeResponse.getStatusLine().getStatusCode() == 200) {
					InputStream is = erCodeResponse.getEntity().getContent();
                    byte[] bytes = new byte[1024];
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    int count = 0;
                    while ((count = is.read(bytes)) != -1) {
                        bos.write(bytes, 0, count);
                    }
                    byte[] byteArray = bos.toByteArray();
                    Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                            byteArray.length);
					
				}
				
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public static String setCookie(HttpResponse httpResponse){
		Map<String, String> cookieMap = new HashMap<String, String>(64);
		System.out.println("----setCookieStore");
		Header[] headers = httpResponse.getHeaders("Set-Cookie");
		if (headers == null || headers.length == 0) {
			System.out.println("----there are no cookies");
			return null;
		}
		String cookie = "";
		for (int i = 0; i < headers.length; i++) {
			cookie += headers[i].getValue();
			if (i != headers.length - 1) {
				cookie += ";";
			}
		}

		String cookies[] = cookie.split(";");
		for (String c : cookies) {
			c = c.trim();
			if (cookieMap.containsKey(c.split("=")[0])) {
				cookieMap.remove(c.split("=")[0]);
			}
			cookieMap.put(
					c.split("=")[0],
					c.split("=").length == 1 ? ""
							: (c.split("=").length == 2 ? c.split("=")[1] : c
									.split("=", 2)[1]));
		}
		System.out.println("----setCookieStore success");
		String cookiesTmp = "";
		for (String key : cookieMap.keySet()) {
			cookiesTmp += key + "=" + cookieMap.get(key) + ";";
		}
		return cookiesTmp.substring(0, cookiesTmp.length() - 2);
	}

	public void httpUrlConnectionGetTest() {

		try {
			URL url = new URL(
					"http://photocdn.sohu.com/20100125/Img269812337.jpg");
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5 * 1000);
			conn.setRequestMethod("GET");
			if (conn.getResponseCode() != 200)
				throw new RuntimeException("Exception!");
			InputStream is = conn.getInputStream();
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
